package com.example.zhanglinqianhui

import Student
import StudentAdapter
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.widget.Button
import java.io.*

class MainActivity : AppCompatActivity() {
    private lateinit var recyclerView: RecyclerView
    private lateinit var studentAdapter: StudentAdapter
    private var studentList: MutableList<Student> = mutableListOf()
    private val ADD_STUDENT_REQUEST = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        recyclerView = findViewById(R.id.recyclerView)
        val addButton: Button = findViewById(R.id.addButton)

        // 设置 RecyclerView
        recyclerView.layoutManager = LinearLayoutManager(this)
        studentAdapter = StudentAdapter(studentList)
        recyclerView.adapter = studentAdapter

        loadStudents() // 从文件加载学生

        addButton.setOnClickListener {
            val intent = Intent(this, AddStudentActivity::class.java)
            startActivityForResult(intent, ADD_STUDENT_REQUEST)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == ADD_STUDENT_REQUEST && resultCode == RESULT_OK) {
            data?.let {
                val student: Student = it.getSerializableExtra("student") as Student
                studentList.add(student)
                studentAdapter.notifyDataSetChanged()
                saveStudents() // 保存学生信息到文件
            }
        }
    }

    private fun loadStudents() {
        try {
            val fis = openFileInput("students.txt")
            val ois = ObjectInputStream(fis)
            studentList = ois.readObject() as MutableList<Student>
            studentAdapter.updateStudentList(studentList)
            ois.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun saveStudents() {
        try {
            val fos = openFileOutput("students.txt", MODE_PRIVATE)
            val oos = ObjectOutputStream(fos)
            oos.writeObject(studentList)
            oos.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}
